<template>
  <view class="workbench-container">
    <view class="workbench-tabs">
      <view 
        class="tab-item" 
        :class="{ 'active': activeTab === '我的任务' }"
        @click="activeTab = '我的任务'"
      >我的任务</view>
      <view 
        class="tab-item" 
        :class="{ 'active': activeTab === '接单中心' }"
        @click="activeTab = '接单中心'"
      >接单中心</view>
    </view>

    <!-- 我的任务 -->
    <view v-if="activeTab === '我的任务'" class="order-list">
      <view 
        v-for="(order, index) in sortedOrderList" 
        :key="index" 
        class="available-order-item"
        :class="{'order-completed': order.status === 1}"
      >
        <view class="available-order-header">
          <text class="available-order-number">订单号：{{ order.orderId }}</text>
          <text class="available-order-time">{{ order.createTime }}</text>
        </view>
        <view class="available-order-location">
          <text>{{ order.cityName }}{{ order.districtName }}（{{ order.address }}）</text>
        </view>
        <view class="available-order-contact">
          <text class="contact-info">
            {{ order.userName || '未知用户' }} 
            {{ order.phone || '未知电话' }}
          </text>
          <view class="order-footer">
            <text class="order-quantity">距离目的地：{{ order.distance }}km</text>
            <view class="order-actions">
              <text 
                v-if="order.status === 0" 
                class="action-btn complete-btn"
                @click="completeOrder(order)"
              >完成配送</text>
              <text 
                v-if="order.status === 1" 
                class="action-btn completed-btn"
              >已完成</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 接单中心 -->
    <view v-else-if="activeTab === '接单中心'" class="order-center">
      <view class="order-center-header">
        <text class="order-center-title">可接单数量：{{ availableOrderCount }}</text>
      </view>
      <view class="available-order-list">
        <view 
          v-for="(order, index) in availableOrders" 
          :key="index" 
          class="available-order-item"
          :class="{'order-selected': isOrderSelected(order)}"
        >
          <view class="available-order-content">
            <view class="available-order-header">
              <text class="available-order-number">订单号：{{ order.orderId }}</text>
              <text class="available-order-time">{{ order.createTime }}</text>
            </view>
            <view class="available-order-location">
              <text>{{ order.cityName }}{{ order.districtName }}（{{ order.address }}）</text>
            </view>
            <view class="available-order-contact">
              <text class="contact-info">
                {{ order.userName || '未知用户' }} 
                {{ order.phone || '未知电话' }}
              </text>
              <view class="order-footer">
                <text class="order-quantity">距离目的地：{{ order.distance }}km</text>
              </view>
            </view>
          </view>
          <view 
            class="order-checkbox" 
            @click="toggleOrderSelection(order)"
          >
            <text class="checkbox" :class="{'checked': isOrderSelected(order)}"></text>
          </view>
        </view>
      </view>
      
      <!-- 底部选择栏 -->
      <view class="bottom-selection-bar">
        <view 
          class="select-all-btn" 
          @click="toggleSelectAllOrders"
        >
          <text class="checkbox" :class="{'checked': isAllOrdersSelected}"></text>
          <text>全选</text>
        </view>
        <text 
          class="receive-all-btn" 
          @click="receiveSelectedOrders"
          :class="{'disabled': selectedOrders.length === 0}"
        >一键接单</text>
      </view>
    </view>
  </view>
</template>

<script>
import { request } from '@/utils/request'

export default {
  data() {
    return {
      activeTab: '我的任务',
      orderList: [],
      availableOrders: [],
      availableOrderCount: 0,
      selectedOrders: [],
      isAllOrdersSelected: false
    }
  },
  computed: {
    sortedOrderList() {
      if (!this.orderList) return []
      
      // 先按状态排序（未完成在前），再按创建时间倒序
      return this.orderList
        .sort((a, b) => {
          // 未完成的订单（status === 0）优先排序
          if (a.status === 0 && b.status === 1) return -1
          if (a.status === 1 && b.status === 0) return 1
          
          // 状态相同时，按创建时间倒序
          return new Date(b.createTime) - new Date(a.createTime)
        })
    }
  },
  onShow() {
    this.fetchOrderList()
    this.fetchAvailableOrders()
  },
  methods: {
    async fetchOrderList() {
      try {
        const res = await request({
          url: '/courier/my-orders',
          method: 'GET',
          data: {
            courierAccount: uni.getStorageSync('courierAccount')
          }
        })
        if (res.code === 200) {
          this.orderList = res.data
        }
      } catch (err) {
        console.error('获取我的任务订单失败:', err)
        uni.showToast({
          title: '获取订单失败',
          icon: 'none'
        })
      }
    },
    async fetchAvailableOrders() {
      try {
        const res = await request({
          url: '/courier/available-orders',
          method: 'GET',
          data: {
            courierAccount: uni.getStorageSync('courierAccount')
          }
        })
        if (res.code === 200) {
          this.availableOrders = res.data
          this.availableOrderCount = res.data.length
          
          // 重置选择状态
          this.selectedOrders = []
          this.isAllOrdersSelected = false
        }
      } catch (err) {
        console.error('获取可接订单失败:', err)
        uni.showToast({
          title: '获取可接订单失败',
          icon: 'none'
        })
      }
    },
    async completeOrder(order) {
      try {
        const res = await request({
          url: '/courier/complete-order',
          method: 'POST',
          data: {
            orderId: order.orderId
          }
        })

        if (res.code === 200) {
          // 将订单状态更新为已完成（1）
          order.status = 1
          
          uni.showToast({
            title: '配送完成',
            icon: 'success'
          })
          
          // 刷新订单列表
          this.fetchOrderList()
        }
      } catch (err) {
        console.error('完成订单失败:', err)
        uni.showToast({
          title: '完成订单失败',
          icon: 'none'
        })
      }
    },
    toggleSelectAllOrders() {
      this.isAllOrdersSelected = !this.isAllOrdersSelected
      if (this.isAllOrdersSelected) {
        this.selectedOrders = this.availableOrders.map(order => order.orderId)
      } else {
        this.selectedOrders = []
      }
    },
    isOrderSelected(order) {
      return this.selectedOrders.includes(order.orderId)
    },
    toggleOrderSelection(order) {
      if (this.isAllOrdersSelected) {
        this.selectedOrders = []
      }
      if (this.selectedOrders.includes(order.orderId)) {
        this.selectedOrders = this.selectedOrders.filter(id => id !== order.orderId)
      } else {
        this.selectedOrders.push(order.orderId)
      }
    },
    async receiveSelectedOrders() {
      if (this.selectedOrders.length === 0) {
        uni.showToast({
          title: '请选择要接单的订单',
          icon: 'none'
        })
        return
      }

      try {
        const res = await request({
          url: '/courier/receive-orders',
          method: 'POST',
          data: {
            orderIds: this.selectedOrders,
            courierAccount: uni.getStorageSync('courierAccount')
          }
        })

        if (res.code === 200) {
          uni.showToast({
            title: '已接收选中的订单',
            icon: 'success'
          })
          this.fetchAvailableOrders()
          this.fetchOrderList()
          
          // 重置选择状态
          this.selectedOrders = []
          this.isAllOrdersSelected = false
        }
      } catch (err) {
        console.error('接收选中的订单失败:', err)
        uni.showToast({
          title: '接收选中的订单失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style scoped>
/* 样式与分拣员工作台基本一致，可以直接复用 */
/* 这里省略具体样式，与sorterWorkbench.vue的样式相同 */
</style> 